package com.yueshop.order.web;

import com.yueshop.order.exception.NoStockException;
import com.yueshop.order.service.OrderService;
import com.yueshop.order.vo.OrderConfirmVo;
import com.yueshop.order.vo.OrderSubmitResponseVo;
import com.yueshop.order.vo.OrderSubmitVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.concurrent.ExecutionException;

@Controller
public class OrderWebController {

    @Autowired
    OrderService orderService;

    //跳转到订单确认页
    @GetMapping("/toTrade")
    public String  toTrad(Model model) throws ExecutionException, InterruptedException {
        OrderConfirmVo orderConfirmVo = orderService.orderConfirm();
        model.addAttribute("data",orderConfirmVo);
        return "confirm";
    }


    @PostMapping("/submitOrder")
    public String submitOrder(OrderSubmitVo orderSubmitVo, Model model, RedirectAttributes redirectAttributes){
        try {
            OrderSubmitResponseVo orderSubmitResponseVo =orderService.submitOrder(orderSubmitVo);
            //下单:创建订单, 验证令牌 验证价格 锁定库存
            //下单成功 来到支付页面
            if(orderSubmitResponseVo.getCode()==0){
                model.addAttribute("vo",orderSubmitResponseVo);
                return "pay";
            }else{
                String msg = "下单失败:";
                  //下单不成功 回到订单确认页重新确认订单
                switch (orderSubmitResponseVo.getCode()){
                    case 1: msg+="订单信息过期,请刷新后再次提交";break;
                    case 2:msg+="订单中的价格发生了变化, 请求刷新后再次提交";break;
                    case 21000:msg+="库存锁定失败,商品库存不足";break;
                }
                redirectAttributes.addFlashAttribute("msg",msg);
                return "redirect:http://order.yueshop.com/toTrade";
            }
        } catch (Exception e) {
            e.printStackTrace();
           if(e instanceof NoStockException){
               String message = e.getMessage();
               redirectAttributes.addFlashAttribute("msg",message);
           }
            return "redirect:http://order.yueshop.com/toTrade";
        }
    }






}
